package com.ambitor.ipro.labelParser;

import java.util.ArrayList;
import java.util.List;

import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.exceptions.ProException;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.ResultCode;
import com.taobao.api.domain.Item;

public class HighPvlabelParser extends IntellLabelParser {

	@Override
	@SuppressWarnings("unchecked")
	public List<Item> parse() throws ProException {
		int num = this.getNum();
		IData userSession = this.getUserSession();
		String userId = userSession.getString("USER_ID");
		String nick = userSession.getString("NICK");
		String sessionId = userSession.getString("SESSION_ID");
		TopService topService = this.getTopService();
		String sql = "SELECT iid,sum(pageview)  FROM tf_s_pv_total_day t"
				+ " where user_id= :USER_ID and iid<> '0' and iid <>'' "
				+ "group by iid order by sum(pageview) desc" + " limit :NUM";
		IData param = new DataMap();
		param.put("USER_ID", userId);
		param.put("NUM", num);
		IDataset dataset = null;
		try {
			dataset = this.getSuperDao().queryListBySql(sql, param);
		} catch (Exception e) {
			throw new ProException(ResultCode.DB_EXCEPTION, "获取高流量宝贝时发生数据库异常",
					e);
		}

		List<Item> highPvItemList = new ArrayList<Item>();
		for (int i = 0; i < dataset.size(); i++) {
			IData data = null;
			try {
				data = dataset.getData(i);
			} catch (Exception e) {
				throw new ProException(ResultCode.EXCEPTION, "", e);
			}
			String iid = data.getString("IID");
			Item item = topService.getItem(sessionId, nick, iid);
			highPvItemList.add(item);
		}

		int minus = this.getNum() - dataset.size();
		if (minus <= 0) {
			return highPvItemList;
		}

		IntellLabelParser parser = new SalableLabelParser(topService,
				userSession, num);
		List<Item> SalableItemList = parser.parse();
		int i = 0;
		List<Item> tempItemList = new ArrayList<Item>();
		for (Item salableItem : SalableItemList) {
			if (i == minus)
				break;
			boolean isExists = false;
			for (Item highPvItem : highPvItemList) {
				if (salableItem.getNumIid().equals(highPvItem.getNumIid())) {
					isExists = true;
					break;
				}
			}
			if (isExists == false) {
				tempItemList.add(salableItem);
				i++;
			}
		}
		highPvItemList.addAll(tempItemList);
		return highPvItemList;
	}
}
